package com.lanou.tipsy.activity;

import android.app.ActionBar;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.toolbox.ImageLoader;
import com.lanou.tipsy.MusicIdle;
import com.lanou.tipsy.R;
import com.lanou.tipsy.adapter.playerLists.LocalListAdapter;
import com.lanou.tipsy.adapter.playerLists.PlayerListsAdapter;
import com.lanou.tipsy.base.BaseActivity;
import com.lanou.tipsy.base.BaseApplication;
import com.lanou.tipsy.data.MyEventBus;
import com.lanou.tipsy.entity.playerList.personal.PersonalList;

import com.lanou.tipsy.tools.lrc.LyricAdapter;
import com.lanou.tipsy.tools.lrc.LyricLoadHelper;
import com.lanou.tipsy.tools.lrc.LyricSentence;
import com.lanou.tipsy.db.DaoMaster;
import com.lanou.tipsy.db.DaoSession;
import com.lanou.tipsy.db.TipsyEntity;
import com.lanou.tipsy.db.TipsyEntityDao;
import com.lanou.tipsy.service.MyService;
import com.lanou.tipsy.tools.myConfig.MyConfig;
import com.lanou.tipsy.tools.volley.DaoSingleton;
import com.lanou.tipsy.tools.volley.VolleySingleton;

import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Create by FengJun on 15/10/28.
 * 音乐播放界面
 */
public class PlayerActivity extends BaseActivity implements View.OnClickListener {
    public static final String TAG = "PlayerActivity";
    private ListView songListLv;//歌曲列表
    private ImageView playBtn, previousBtn, nextBtn, stopBtn, songsListBtn;
    private SeekBar seekBar;//定义一个进度条
    private TextView singerTv, songTv, positionTv;//歌曲名字,歌手名字
    private TextView listSizeTv;//歌曲列表长度
    private String songUrl;//歌曲网址
    private MusicIdle musicIdle;//定义aidl
    private Intent intent;
    private TextView progressTv, maxTv;//当前进度,最大进度
    private boolean isUser = true;//是否是用户点得收藏
    //链接service
    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            musicIdle = MusicIdle.Stub.asInterface(service);

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
    //我的歌曲列表
    private ArrayList<PersonalList> songsLists;//集合
    private PersonalList songsList;//实体类
    private PlayerListsAdapter playerListsAdapter;//适配器
    private int position;//当前播放的歌曲的position
    private ImageView backIv;
    //设置播放模式
    private String[] modeType = {"单曲循环", "随机播放", "循环播放", "顺序播放"};
    private int[] modePicture = {R.mipmap.bg_mode_single_on, R.mipmap.bg_mode_random_on,
            R.mipmap.bg_mode_loop_on, R.mipmap.bg_mode_list_on};
    private int flag = 0;
    private ImageView modeIv;
    private String modeFlag;//设置播放模式
    private Bitmap bitmap;//本地歌曲图片
    private String pictureUrl;//网络歌曲图片
    private String tag;//区分本地歌曲和网络歌曲
    private ImageLoader imageLoader;

    //歌词
    private ListView lrcLv;//歌词listview
    private TextView lrcEmptyTv;//没有歌词时显示
    private LyricLoadHelper mLyricLoadHelper;//下载歌词helper类
    private LyricAdapter mLyricAdapter;//歌词适配器
    private TextView loadLrcTv;//点击显示歌词
    private String musicName;
    private int timerProgress;
    private int timerMax;
    private String[] showControl = {"词", "图"};
    private int showFlag = 0;
    private ImageView backgroundIv;


    //收藏-greendao
    private SQLiteDatabase db;//数据库
    private DaoMaster mDaMaster;//管理者
    private DaoSession mDaoSession;//会话
    //对应的表,由java代码生成的,对数据库内相应的表操作使用此对象
    private TipsyEntityDao tipsyEntityDao;
    //数据库的实体类
    private TipsyEntity tipsyEntity;
    //定义选择按钮
    private CheckBox checkCollect;
    private String songTitle;//歌曲名
    private String singerName;//歌手名
    private ArrayList<TipsyEntity> tipsyEntities;
    private Boolean isChecked;//是否是用户boolean判断


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_player);

        //服务
        intent = new Intent(this, MyService.class);
        startService(intent);//运行服务
        bindService(intent, conn, BIND_AUTO_CREATE);//绑定服务
        EventBus.getDefault().register(this);//注册eventBus

        //调用控件初始化的方法
        initView();
    }


    //设置当前播放的模式
    @Override
    protected void onResume() {
        super.onResume();
        modeFlag = MyConfig.getSharePreStr(PlayerActivity.this, "playingMode", "currentMode");
        Log.i("test", "modeFlag:" + modeFlag);
        switch (modeFlag) {
            case "looping":
                modeIv.setImageResource(modePicture[2]);
                Toast.makeText(PlayerActivity.this, modeType[2], Toast.LENGTH_SHORT).show();
                break;
            case "single":
                modeIv.setImageResource(modePicture[0]);
                Toast.makeText(PlayerActivity.this, modeType[0], Toast.LENGTH_SHORT).show();
                break;
            case "random":
                modeIv.setImageResource(modePicture[1]);
                Toast.makeText(PlayerActivity.this, modeType[1], Toast.LENGTH_SHORT).show();
                break;
            case "sequence":
                modeIv.setImageResource(modePicture[3]);
                Toast.makeText(PlayerActivity.this, modeType[3], Toast.LENGTH_SHORT).show();
                break;
            default:
                modeIv.setImageResource(modePicture[2]);
                Toast.makeText(PlayerActivity.this, modeType[2], Toast.LENGTH_SHORT).show();
                break;
        }

    }

    //初始化控件->给控件添加监听

    private void initView() {
        imageLoader = VolleySingleton.getInstance().getImageLoader();
        playBtn = (ImageView) findViewById(R.id.iv_play);//播放
        previousBtn = (ImageView) findViewById(R.id.iv_previous);//上一首
        nextBtn = (ImageView) findViewById(R.id.iv_next);//下一首
        seekBar = (SeekBar) findViewById(R.id.sb_progress);//进度条
        songsListBtn = (ImageView) findViewById(R.id.iv_list);//歌曲列表
        singerTv = (TextView) findViewById(R.id.tv_player_singer);//歌手
        songTv = (TextView) findViewById(R.id.tv_player_songs);//歌曲
        progressTv = (TextView) findViewById(R.id.tv_player_progress);//当前进度
        maxTv = (TextView) findViewById(R.id.tv_player_max);//最大进度
        positionTv = (TextView) findViewById(R.id.tv_player_position);//当前位置
        modeIv = (ImageView) findViewById(R.id.iv_mode);
        backIv = (ImageView) findViewById(R.id.iv_back_to_front);
        backgroundIv = (ImageView) findViewById(R.id.iv_player_img);
        //显示歌词的
        lrcLv = (ListView) findViewById(R.id.lv_lrc);
        lrcEmptyTv = (TextView) findViewById(R.id.lyric_empty);
        loadLrcTv = (TextView) findViewById(R.id.tv_load_lrc);
        //初始化helper类
        mLyricLoadHelper = new LyricLoadHelper();
        mLyricLoadHelper.setLyricListener(mLyricListener);

        showFlag = 1;
        loadLrcTv.setText(showControl[showFlag]);//图
        lrcLv.setVisibility(View.VISIBLE);
        backgroundIv.setVisibility(View.GONE);

        //显示歌词的listview绑定适配器
        mLyricAdapter = new LyricAdapter(this);
        lrcLv.setAdapter(mLyricAdapter);
        lrcLv.setEmptyView(lrcEmptyTv);
        lrcLv.startAnimation(AnimationUtils.loadAnimation(PlayerActivity.this, android.R.anim.fade_in));

        //利用单例模式
        checkCollect = (CheckBox) findViewById(R.id.checkCollect);

        //监听
        modeIv.setOnClickListener(this);
        playBtn.setOnClickListener(this);
        previousBtn.setOnClickListener(this);
        nextBtn.setOnClickListener(this);
        songsListBtn.setOnClickListener(this);
        backIv.setOnClickListener(this);
        loadLrcTv.setOnClickListener(this);//下载歌词的监听
        //seekBar进度条接口回调
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                try {
                    musicIdle.setSeekTo(seekBar.getProgress());
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });

        //tipsyEntity初始化
        tipsyEntity = new TipsyEntity();
        tipsyEntityDao = DaoSingleton.getInstance().getTipsyEntityDao();
        checkCollect.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (checkCollect.isChecked() && isUser) {//是用户点击的
                    //tipsyEntity 3个属性进行赋值
                    tipsyEntity.setSingerName(String.valueOf(singerName));
                    tipsyEntity.setSongTitle(String.valueOf(songTitle));
                    tipsyEntity.setTag(tag);
                    tipsyEntityDao.insertOrReplace(tipsyEntity);
                    int size = tipsyEntityDao.loadAll().size();
                    Log.i("test", TAG + "...此条数据库的内容是..." + " " +
                            tipsyEntity.getSingerName() + " " + tipsyEntity.getSongTitle() + " " + tipsyEntity.getTag() + "\n长度 = " + size);
                    Toast.makeText(PlayerActivity.this, "歌曲已收藏", Toast.LENGTH_SHORT).show();
                }
                if (!checkCollect.isChecked()) {
                    tipsyEntityDao.delete(tipsyEntity);
                    Log.i("test", TAG + "数据库删除数据:" + "" + tipsyEntity.getSingerName());
                    Toast.makeText(PlayerActivity.this, "歌曲已取消收藏", Toast.LENGTH_SHORT).show();
                }
                isUser = true;//恢复默认值 方便下次用户点击
            }
        });
        initDatabase();//初始化数据
    }

    //收藏具体操作
    private void initDatabase() {
    }


    //获得当前正在播放的歌曲的position
    public void onEventMainThread(MyEventBus.ListPosition index) {
        this.position = index.getIndex();
        positionTv.setText("" + (position + 1));
    }

    //监听方法的回调
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_play:
                play();//播放歌曲的回调
                break;
            case R.id.iv_previous:
                previous();//上一曲
                break;
            case R.id.iv_next:
                next();//下一曲
                break;
            case R.id.iv_list:
                songsListPopupWindow();//弹出歌曲列表
                break;
            case R.id.iv_mode:
                chooseMode();//选择播放模式
                break;
            case R.id.iv_back_to_front:
                finish();//返回上一页
                overridePendingTransition(R.anim.translate_vx_in, R.anim.translate_vx_out);
                break;
            case R.id.tv_load_lrc://显示歌词和图片的方法
                showControl();
                break;
        }
    }

    private void showControl() {
        switch (showFlag) {
            case 0:
                showFlag++;
                loadLrcTv.setText(showControl[showFlag]);//图
                lrcLv.setVisibility(View.VISIBLE);
                backgroundIv.setVisibility(View.GONE);
                break;
            case 1:
                showFlag = 0;
                loadLrcTv.setText(showControl[showFlag]);//词
                backgroundIv.setVisibility(View.VISIBLE);
                lrcLv.setVisibility(View.GONE);
                if (tag.equals("网络歌曲")) {
                    ImageLoader.ImageListener listener = ImageLoader.getImageListener(backgroundIv,
                            R.mipmap.logo_2, R.mipmap.error);
                    try {
                        imageLoader.get(pictureUrl, listener);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else if (tag.equals("本地歌曲")) {
                    backgroundIv.setImageBitmap(bitmap);
                }
                break;
            default:
                break;
        }
    }

    //选择播放模式
    private void chooseMode() {
        switch (flag) {
            case 0:
                flag++;
                modeFlag = "random";
                modeIv.setImageResource(modePicture[flag]);
                Toast.makeText(PlayerActivity.this, modeType[flag], Toast.LENGTH_SHORT).show();
                break;
            case 1:
                flag++;
                modeFlag = "looping";
                modeIv.setImageResource(modePicture[flag]);
                Toast.makeText(PlayerActivity.this, modeType[flag], Toast.LENGTH_SHORT).show();
                break;
            case 2:
                flag++;
                modeFlag = "sequence";
                modeIv.setImageResource(modePicture[flag]);
                Toast.makeText(PlayerActivity.this, modeType[flag], Toast.LENGTH_SHORT).show();
                break;
            case 3:
                flag = 0;
                modeFlag = "single";
                modeIv.setImageResource(modePicture[flag]);
                Toast.makeText(PlayerActivity.this, modeType[flag], Toast.LENGTH_SHORT).show();
                break;
            default:
                flag = 2;
                modeFlag = "looping";
                modeIv.setImageResource(modePicture[2]);
                Toast.makeText(PlayerActivity.this, modeType[2], Toast.LENGTH_SHORT).show();
                break;
        }
        EventBus.getDefault().post(new MyEventBus.CurrentMode(modeFlag));
        Log.i("test", TAG + "->current->playMode:" + modeFlag);
        MyConfig.putSharePre(PlayerActivity.this, "playingMode", "currentMode", modeFlag);
    }

    //onEvent->我的歌曲列表
    public void onEventMainThread(MyEventBus.PersonalLists personalLists) {
        this.songsLists = personalLists.getPersonalLists();
        playerListsAdapter = new PlayerListsAdapter(songsLists, PlayerActivity.this, position);
    }

    //获得本地歌曲的图片uri
    public void onEventMainThread(MyEventBus.SetLocalPicture picture) {
        bitmap = picture.getImageUri();
    }

    //获得网络歌曲的图片url
    public void onEventMainThread(MyEventBus.SetNetPitcure picture) {
        pictureUrl = picture.getImageUrl();
    }

    //获得歌曲名字,歌手,tag
    public void onEventMainThread(MyEventBus.SetSongInfo songInfo) {
        //Log.i("test", "PlayerActivity->onEventMainThread(songInfo");
        musicName = songInfo.getSongs();
        songTv.setText(songInfo.getSongs());
        songTitle = songInfo.getSongs();
        singerTv.setText(songInfo.getSinger());
        singerName = songInfo.getSinger();//歌手名
        tag = songInfo.getTag();
        if (showFlag == 1) {
            // 取得歌曲同目录下的歌词文件绝对路径
            String lyricFilePath = BaseApplication.lrcPath + "/" + musicName + ".lrc";
            mLyricLoadHelper.loadLyric(lyricFilePath);
        } else if (showFlag == 0) {
            mLyricLoadHelper.loadLyric(null);
        }
        if (songTitle != null && songTitle != "") {//数据库里已经有了
            List<TipsyEntity> tipsyEntities = tipsyEntityDao.queryBuilder().where(TipsyEntityDao.Properties.SongTitle.eq(songTitle)).list();
            //Log.i("test", TAG + "->查找数据库后:" + tipsyEntities);
            if (tipsyEntities.size() > 0 && tipsyEntities != null) {
                //count++;
                isUser = false;//不是用户点击的
                checkCollect.setChecked(true);
                checkCollect.setClickable(false);
            } else {
                isUser = true;
                checkCollect.setChecked(false);
            }
        }
    }

    //歌曲列表popupwindow
    private void songsListPopupWindow() {
        //定义一个popupWindow
        final PopupWindow popupWindow = new PopupWindow(this);
        //加载布局文件
        View view = getLayoutInflater().inflate(R.layout.fr_player_lists, null);
        songListLv = (ListView) view.findViewById(R.id.lv_player_lists);
        listSizeTv = (TextView) view.findViewById(R.id.tv_player_list_size);
        //设置歌曲列表适配器
        try {
            songListLv.setAdapter(playerListsAdapter);
        } catch (Exception e) {
            e.printStackTrace();
        }
        //设置歌曲列表的长度
        if (songsLists != null && songsLists.size() > 0) {
            listSizeTv.setText("/" + songsLists.size() + "首");
        } else {
            listSizeTv.setVisibility(View.GONE);
        }
        //歌曲列表行布局监听
        songListLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                songsList = (PersonalList) parent.getItemAtPosition(position);
                Toast.makeText(PlayerActivity.this, songsList.getSongTitle(), Toast.LENGTH_SHORT).show();
                EventBus.getDefault().post(new MyEventBus.NetSongs(playerListsAdapter.getDatas(), position));
                popupWindow.dismiss();
            }
        });
        popupWindow.setContentView(view);
        popupWindow.setWidth(ActionBar.LayoutParams.WRAP_CONTENT);
        popupWindow.setHeight(500);
        popupWindow.setOutsideTouchable(true);//设置非popuWindow区域可出
        popupWindow.setFocusable(true);//设置是否可以获得焦点
        popupWindow.setTouchable(true);//设置是否可以被触摸
        popupWindow.showAtLocation(view, Gravity.BOTTOM | Gravity.RIGHT, 0, 150);
    }

    //播放
    private void play() {
        if (musicIdle != null) {
            try {
                if (musicIdle.isPlaying()) {
                    musicIdle.pause();
                    playBtn.setImageResource(R.mipmap.nowplayplay_normal);
                } else {
                    musicIdle.play();
                    playBtn.setImageResource(R.mipmap.nowplaypause_normal);
                }
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    //上一曲
    private void previous() {
        if (musicIdle != null) {
            try {
                musicIdle.previous();//调用aidl里面的方法
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    //下一曲
    private void next() {
        if (musicIdle != null) {
            try {
                musicIdle.next();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    //进度条->刷新当前进度
    public void onEventMainThread(MyEventBus.CurrentProgress progress) {
        timerProgress = progress.getCurrentProgress();
        if (progress.getCurrentProgress() == 0) {
            seekBar.setProgress(0);
        } else {
            seekBar.setProgress(progress.getCurrentProgress());
            progressTv.setText(LocalListAdapter.formatTime((long) progress.getCurrentProgress()));
        }
    }

    //进度条->获得最大进度
    public void onEventMainThread(MyEventBus.MaxProgress max) {
        timerMax = max.getMaxProgress();
        if (max.getMaxProgress() == 0) {
            seekBar.setMax(100);
        } else {
            seekBar.setMax(max.getMaxProgress());
            maxTv.setText(LocalListAdapter.formatTime((long) max.getMaxProgress()));
            refreshSeekProgress(timerProgress, timerMax);
        }
        if (timerProgress == timerMax) {
            lrcLv.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i("test", "onDestory()");
        unbindService(conn);
        EventBus.getDefault().unregister(this);
    }

    //从loadHelper类调用下载歌词的方法,同时显示
    private LyricLoadHelper.LyricListener mLyricListener = new LyricLoadHelper.LyricListener() {

        @Override
        public void onLyricLoaded(List<LyricSentence> lyricSentences, int index) {
            if (lyricSentences != null) {
                mLyricAdapter.setLyric(lyricSentences);
                mLyricAdapter.setCurrentSentenceIndex(index);
                mLyricAdapter.notifyDataSetChanged();
                // 本方法执行时，lyricshow的控件还没有加载完成，所以延迟下再执行相关命令
            }
        }

        @Override
        public void onLyricSentenceChanged(int indexOfCurSentence) {
            mLyricAdapter.setCurrentSentenceIndex(indexOfCurSentence);
            mLyricAdapter.notifyDataSetChanged();
            lrcLv.smoothScrollToPositionFromTop(indexOfCurSentence,
                    lrcLv.getHeight() / 2, 500);
        }
    };

    public void refreshSeekProgress(int curTime, int totalTime) {

        int tempCurTime = curTime;

        curTime /= 1000;
        totalTime /= 1000;
        int curminute = curTime / 60;
        int cursecond = curTime % 60;

        String curTimeString = String.format("%02d:%02d", curminute, cursecond);

        int rate = 0;
        if (totalTime != 0) {
            rate = (int) ((float) curTime / totalTime * 100);
        }
        mLyricLoadHelper.notifyTime(tempCurTime);
    }
}
